package com.qw.badge.sample

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationCompat

/**
 * Created by qinwei on 2021/6/20 4:51 下午
 * email: qinwei_it@163.com
 */
class XiaomiBadge : IBadge {
    override fun setBadgeNum(context: Context, num: Int) {
        if(num<=0)return
        createNotificationChannel(context)
        val builder = NotificationCompat.Builder(context, "101")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Title")
            .setContentText("Text")
            .setNumber(num)
            .setPriority(NotificationCompat.PRIORITY_MAX)
        val notificationManager: NotificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val notification = builder.build()
        val field = notification.javaClass.getDeclaredField("extraNotification");
        val extraNotification = field.get(notification)
        val method =
            extraNotification.javaClass.getDeclaredMethod("setMessageCount", Int::class.java)
        method.invoke(extraNotification, num)
        notificationManager.notify(1000, notification)
    }

    private fun createNotificationChannel(context: Context) {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "channel_im"
            val descriptionText = "channel_im"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel("101", name, importance).apply {
                description = descriptionText
            }
            // Register the channel with the system
            val notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }
}